package com.knoya.chejian.pda.util;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import com.knoya.chejian.pda.Myapp;
import com.knoya.chejian.pda.R;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by honjane on 2016/9/11.
 */

public class FileUtils {

    private static String APP_DIR_NAME = "honjane";
    private static String FILE_DIR_NAME = "files";
    private static String mRootDir;
    private static String mAppRootDir;
    private static String mFileDir;

    public static void init() {
        mRootDir = getRootPath();
        if (mRootDir != null && !"".equals(mRootDir)) {
            mAppRootDir = mRootDir + "/" + APP_DIR_NAME;
            mFileDir = mAppRootDir + "/" + FILE_DIR_NAME;
            File appDir = new File(mAppRootDir);
            if (!appDir.exists()) {
                appDir.mkdirs();
            }
            File fileDir = new File(mAppRootDir + "/" + FILE_DIR_NAME);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }

        } else {
            mRootDir = "";
            mAppRootDir = "";
            mFileDir = "";
        }
    }

    public static String getFileDir(){
        return mFileDir;
    }


    public static String getRootPath() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            return Environment.getExternalStorageDirectory().getAbsolutePath(); // filePath:  /sdcard/
        } else {
            return Environment.getDataDirectory().getAbsolutePath() + "/data"; // filePath:  /data/data/
        }
    }

    /**
     * 打开文件
     * 兼容7.0
     *
     * @param context     activity
     * @param file        File
     * @param contentType 文件类型如：文本（text/html）
     *                    当手机中没有一个app可以打开file时会抛ActivityNotFoundException
     */
    public static void startActionFile(Context context, File file, String contentType) throws ActivityNotFoundException {
        if (context == null) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);//增加读写权限
        intent.setDataAndType(getUriForFile(context, file), contentType);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    /**
     * 打开相机
     * 兼容7.0
     *
     * @param activity    Activity
     * @param file        File
     * @param requestCode result requestCode
     */
    public static void startActionCapture(Activity activity, Fragment fragment, File file, int requestCode) {
        if (fragment== null) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, getUriForFile(activity, file));
            activity.startActivityForResult(intent, requestCode);
        }else if(fragment!=null){
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, getUriForFile(activity, file));
            fragment.startActivityForResult(intent, requestCode);
        }
        Log.e("TAAAG",file.toString());
    }


    public static Uri getUriForFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context.getApplicationContext(), "com.knoya.chejian.pda.fileProvider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }
    public static Uri getUriForFile(Fragment context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context.getActivity().getApplicationContext(), "com.knoya.chejian.pda.fileProvider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }
    /**生成文件*/

    public static File makeFilePath(String filePath, String fileName) {

        File file = null;

        makeRootDirectory(filePath);

        try {

            file = new File(filePath + fileName);

            if (!file.exists()) {

                file.createNewFile();

            }else{
                file.delete();
                file.createNewFile();
            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        return file;

    }
    // 生成文件夹
    public static void makeRootDirectory(String filePath) {

        File file = null;

        try {

            file = new File(filePath);

            if (!file.exists()) {

                file.mkdir();

            }
        } catch (Exception e) {

            Log.i("error:", e+"");


        }

    }
    /**
     * 将字符串写入到文本文件中
     */
    public static void writeTxtToFile(String strcontent, String filePath, String fileName) {

        //生成文件夹之后，再生成文件，不然会出错

        makeFilePath(filePath, fileName);


        String strFilePath = filePath + fileName;

        // 每次写入时，都换行写

        String strContent = strcontent + "\r\n";

        try {

            File file = new File(strFilePath);

            if (!file.exists()) {

                Log.d("TestFile", "Create the file:" + strFilePath);

                file.getParentFile().mkdirs();

                file.createNewFile();

            }

            RandomAccessFile raf = new RandomAccessFile(file, "rwd");

            raf.seek(file.length());

            raf.write(strContent.getBytes());

            raf.close();

        } catch (Exception e) {

            Log.e("TestFile", "Error on write File:" + e);

        }

    }

    public List<String> fenge(String data){
        List<String> datas = new ArrayList<>();
        String[] ss = data.split("}");
        for(int i = 0 ; i < ss.length; i++){
            String[] bb = ss[i].split("\\{");
            if(bb.length>0){
                datas.add(bb[0]);
            }
        }
        return datas;
    }

    /**
     * 适合播放声音短，文件小
     * 可以同时播放多种音频
     * 消耗资源较小
     */
    public static void playSound(int rawId) {
        SoundPool soundPool;
        if (Build.VERSION.SDK_INT >= 21) {
            SoundPool.Builder builder = new SoundPool.Builder();
            //传入音频的数量
            builder.setMaxStreams(1);
            //AudioAttributes是一个封装音频各种属性的类
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
            //设置音频流的合适属性
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
            builder.setAudioAttributes(attrBuilder.build());
            soundPool = builder.build();
        } else {
            //第一个参数是可以支持的声音数量，第二个是声音类型，第三个是声音品质
            soundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 5);
        }
        //第一个参数Context,第二个参数资源Id，第三个参数优先级
        soundPool.load(Myapp.getContext(), R.raw.baojing, 1);
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                soundPool.play(1, 1, 1, 0, 0, 1);
            }
        });
        //第一个参数id，即传入池中的顺序，第二个和第三个参数为左右声道，第四个参数为优先级，第五个是否循环播放，0不循环，-1循环
        //最后一个参数播放比率，范围0.5到2，通常为1表示正常播放
//        soundPool.play(1, 1, 1, 0, 0, 1);
        //回收Pool中的资源
        //soundPool.release();
    }

}